package com.kqzz.common.exception;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

/**
 * 自定义用户登录认证失败的返回结构，替换框架的默认数据结构(仅使用com.fasterxml.jackson做序列化)
 */
@SuppressWarnings("serial")
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {

	public CustomOauthExceptionSerializer() {
        super(CustomOauthException.class);
    }
	
	@Override
    public void serialize(CustomOauthException value, JsonGenerator gen, SerializerProvider provider) throws IOException {
		String msg = value.getMessage();
		int errorNo = 0;
		if(StringUtils.contains(value.getMessage(), "Invalid scope")){
			msg = "scope参数错误";
		}else if(StringUtils.contains(value.getMessage(), "grant type")){
			msg = "grant_type参数错误或缺失";
		}else if(StringUtils.contains(value.getMessage(), "Bad credentials") 
				|| StringUtils.contains(value.getMessage(), "坏的凭证")){
			msg = "登录失败，请核对账号或密码";
		}else if(StringUtils.contains(value.getMessage(), "天后将到期")){
			errorNo = 99;
		}
//		gen.writeObject(new Response().failure(msg));
		
		gen.writeStartObject();
        gen.writeNumberField("errorNo", errorNo);
        gen.writeStringField("errorMsg", msg);
		
        if (value.getAdditionalInformation()!=null) {
            for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                gen.writeStringField(key, add);
            }
        }
        gen.writeEndObject();
    }	
}
